/***********************************************************
 *  File_Name  : XJMutex.cpp
 *  File_Path   : 
 *  File_Encode : UTF8
 *  Description : 线程互斥锁类
 *  
 *  OS : Linux, UNIX, Windows
 *  LastVersion  : 20110211
 *      
 *  Author      : LiXiujie(李秀杰)
 *  Date        : 2011-2-11
 *  Version     : 20110211
 *  Description : 
 *                
 *  Edit Author : LiXiujie(李秀杰)
 *  Edit Date   : 2014-8-20
 *  Version     : 20140820
 *  Description : support windows
 *                
 ***********************************************************/
#ifndef XJMUTEX_H_
#define XJMUTEX_H_
#include "XJEnv.h"
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <stdexcept>

namespace XJUtilClass{
class XJMutex {
public:
	XJMutex();
	virtual ~XJMutex();
public:
	int Lock();
	int Unlock();
	int TryLock();

#ifndef _WIN32
    pthread_mutex_t* GetMutex()
    {
        return &m_Mutex;
    }
#else
    CRITICAL_SECTION * GetMutex()
    {
        return & m_singlelock;
    }
#endif

private:
#ifndef _WIN32
    pthread_mutex_t m_Mutex;
    pthread_mutexattr_t m_attr;
#else
    CRITICAL_SECTION m_singlelock;
#endif
	bool m_OK;
};

template<class XJLockObj> class XJLocalLock
{
public:
	XJLocalLock(XJLockObj& obj) : m_lock(obj) {m_lock.Lock();}
	~XJLocalLock() {m_lock.Unlock();}
private:
	XJLockObj& m_lock;
};

typedef XJLocalLock<XJMutex> XJMutexLocalLock;

}//namespace XJUtilClass{
#endif /* XJMUTEX_H_ */
